<?php
import( 'de.ceus-media.ui.html.Elements' );
import( 'de.ceus-media.ui.html.FormElements' );
import( 'de.ceus-media.file.yaml.Reader' );
import( 'tools.Setup.classes.BaseSetupScreen' );
class SetupController extends BaseSetupScreen
{
	protected $config		= array();
	protected $path		= "";
	protected $screenID	= 0;
	protected $screens	= null;
	protected $messages	= array();

	function __construct()
	{
		$this->path		= realpath( dirname( dirname( __FILE__ ) ) ).DIRECTORY_SEPARATOR;
		$this->config	= File_Yaml_Reader::load( $this->path."config.yaml" );
		$this->words	= File_Yaml_Reader::load( $this->path."language.yaml" );
		$this->screenID = isset( $_REQUEST['screen'] ) ? (int)$_REQUEST['screen'] : 0;
		session_start();
		if( !$this->getLanguage() )
			$this->setLanguage( array_shift( $this->config['languages'] ) );
		$this->handleAction();
		$this->getView();
	}
	
	function handleAction()
	{
		if( isset( $_REQUEST['action'] ) )
		{
			if( $_REQUEST['action'] == "goBack" )
				if( $this->screenID > 0 )
					return $this->screenID--;
			$screen	= $this->getScreen( $this->screenID );
			try
			{
				if( $screen->handleAction( $_REQUEST['action'] ) )
					$this->screenID++;
			}
			catch( Exception $e )
			{
				$this->saveMessage( $e->getMessage() );
			}
		}
	}
	
	public function saveMessage( $message )
	{
		$this->messages[]	= $message;
	}
	
	private function getMessages()
	{
		return $this->messages;
	}
	
	public function & getConfig()
	{
		return $this->config;
	}
	
	private function getScreen( $screenID )
	{
		$class	= $this->config['screens'][$screenID]['class'];
		import( "tools.Setup.classes.screens.".$class );
		$screen	= new $class( $this->config, $this->words, $screenID, $this->path );
		return $screen;
	}

	private function getView()
	{
		$screen		= $this->getScreen( $this->screenID );
		$ui['content']	= $screen->getView();

		$ui['msg']		= implode( "<br/>", $this->getMessages() );
		ob_start();
		echo "<span style='font-size: x-small'>";
		print_m( $this->config );
		echo "</span>";
		echo "<span style='font-size: x-small'>";
		print_m( $this->words );
		echo "</span>";
		$ui['dump']		= ob_get_clean();
		
		
		for( $i=0; $i<count( $this->config['screens'] ); $i++ )
		{
			$class	= "";
			$screen	= $this->config['screens'][$i];
			$title	= $this->words[$this->getLanguage()][$screen['name']]['title'];
			if( $i == $this->screenID || $i < $this->screenID )
			{
				$class	= $i == $this->screenID ? "current" : "complete";
				$title	= UI_HTML_Elements::Link( "setup.php5?screen=".$i, $title );
			}
			$list[]	= UI_HTML_Elements::ListItem( $title, 0, array( 'class' => $class ) );
		}
		$ui['navi']	= UI_HTML_Elements::unorderedList( $list );

		$ui['config']		= $this->config;
		$ui['words']		= $this->words;

		echo $this->loadTemplate( $ui, "master" );
	}
	
	public function & getWords()
	{
		return $this->words;
	}
}
?>